const express = require('express')
const next = require('next')
const { createProxyMiddleware } = require('http-proxy-middleware')
const routes = require('./routes')

const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
const handler = routes.getRequestHandler(app)

const devProxy = {
    '/api': {
        target: 'http://92.levect.com/api',
        pathRewrite: {
            '^/api': '/'
        },
        changeOrigin: true
    }
}

app.prepare()
    .then(() => {
        const server = express()

        if (dev && devProxy) {
            Object.keys(devProxy).forEach(function (context) {
                server.use(createProxyMiddleware(context, devProxy[context]))
            })
        }

        server.use(handler)

        server.get('*', (req, res) => {
            return handle(req, res)
        })

        server.listen(3000, (err) => {
            if (err) throw err
            console.log('> Ready on http://localhost:3000')
        })
    })